package io.github.lee.app.unsplash.ui.detail.photo

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.graphics.drawable.toDrawable
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import io.github.lee.app.unsplash.databinding.HeaderPhotoDetailBinding
import io.github.lee.app.unsplash.repository.domain.Photo
import io.github.lee.app.unsplash.util.BlurHashDecoder
import io.github.lee.core.ui.adapter.HeaderFooterAdapter
import io.github.lee.core.ui.ba.coilLoad
import kotlin.math.roundToInt

class PhotoDetailHeaderAdapter(data: Photo?) :
    HeaderFooterAdapter<Photo, HeaderPhotoDetailBinding>(data) {
    override fun onCreateDataBinding(
        context: Context,
        inflater: LayoutInflater,
        parent: ViewGroup,
        viewType: Int
    ): HeaderPhotoDetailBinding {
        val vb = HeaderPhotoDetailBinding.inflate(inflater, parent, false)
        val params = StaggeredGridLayoutManager.LayoutParams(
            StaggeredGridLayoutManager.LayoutParams.MATCH_PARENT,
            StaggeredGridLayoutManager.LayoutParams.MATCH_PARENT
        )
        params.isFullSpan = true
        vb.root.layoutParams = params
        return vb
    }


    override fun onItemHolder(binding: HeaderPhotoDetailBinding, item: Photo) {
        binding.ivPhoto.apply {
            isZoomable = true
//            setOnViewDragListener { _, _ -> setAllowParentInterceptOnEdge(scale == 1.0f) }
        }
        val ratio = item.width * 1F / item.height
        val bw = 4
        val bh = (4 / ratio + 0.5).roundToInt()
        val hash = BlurHashDecoder.decode(item.blurHash, bw, bh)
        val placeholder = hash?.toDrawable(context.resources)
        binding.ivPhoto.coilLoad(
            item.urls?.regular, crossfade = 180,
            placeholder = placeholder, error = placeholder
        )

    }

}